﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using log4net;
using log4net.Config;
using System.IO;
namespace Code.Commen
{
    public class Log
    {
        /// <summary>
        /// 指示是否已经初始化了日志记录设置
        /// </summary>
        public static bool IsInit { get; private set; }

        /// <summary>
        /// 初始化日志记录设置
        /// </summary>
        public static void InitLog()
        {
            if (IsInit)
                return;
            try
            {
                var file = ConfigurationManager.AppSettings["log4net_config"] ?? "log4net.config";

                if (!File.Exists(file))
                {
                    if (System.Web.HttpContext.Current != null)
                        file = System.Web.HttpContext.Current.Server.MapPath(file);
                }

                if (System.IO.File.Exists(file))
                {
                    XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(file));
                }
                else
                {
                    var obj = ConfigurationManager.GetSection("log4net");

                    if (obj != null)
                    {
                        XmlConfigurator.Configure(obj as XmlElement);
                    }
                    else
                    {
                        throw new Exception("不存在log4net配置节。");
                    }
                }
            }
            catch (Exception e)
            {
                XmlDocument doc = new XmlDocument();
                string logconfig = "<log4net><root><level value=\"INFO\" /><appender-ref ref=\"LogFileAppender\" /></root><logger name=\"testApp.Logging\">";
                logconfig += "<level value=\"DEBUG\"/></logger><appender name=\"LogFileAppender\" type=\"log4net.Appender.FileAppender\" ><param name=\"File\" value=\"../log-file.txt\" />";
                logconfig += "<param name=\"AppendToFile\" value=\"true\" /><layout type=\"log4net.Layout.PatternLayout\"><param name=\"ConversionPattern\" value=\"%d %-5p %c - %m%n\" />";
                logconfig += "</layout><filter type=\"log4net.Filter.LevelRangeFilter\"><param name=\"LevelMin\" value=\"INFO\" /><param name=\"LevelMax\" value=\"ERROR\" />";
                logconfig += "</filter></appender></log4net>";

                System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.Default.GetBytes(logconfig));

                XmlReader xmlReader = XmlReader.Create(ms);
               
                doc.Load(xmlReader);

                XmlNodeList configNodeList = doc.GetElementsByTagName("log4net");

                XmlConfigurator.Configure(configNodeList[0] as XmlElement);

                ms.Dispose();

                ILog log = LogManager.GetLogger("Code.Commen.Log");
                log.Error("读取日志配置信息时出错，启用默认设置。");
            }
            XmlConfigurator.Configure();

            IsInit = true;
        }

        /// <summary>
        /// 获取日志记录对象
        /// </summary>
        /// <param name="type">所调用的类</param>
        /// <returns></returns>
        public static ILog GetLog(Type type)
        {
            if (!IsInit)
                InitLog();
            return LogManager.GetLogger(type);
        }
        /// <summary>
        /// 获取日志记录对象
        /// </summary>
        /// <param name="name">所调用的类的全称 包含名名空间 如:Code.Commen.Log</param>
        /// <returns></returns>
        public static ILog GetLog(string name)
        {
            if (!IsInit)
                InitLog();
            return LogManager.GetLogger(name);
        }

        public static ILog GetLog<T>()
        {
            return GetLog(typeof(T));
        }
    }
}
